package org.example.iris.service.impl;

import org.example.iris.mapper.ResumeFileMapper;
import org.example.iris.mapper.StudentFileMapper;
import org.example.iris.mapper.StudentMapper;
import org.example.iris.mapper.UploadLogMapper;
import org.example.iris.entity.File;
import org.example.iris.entity.Student;
import org.example.iris.entity.UploadLog;
import org.example.iris.service.FileService;
import org.example.iris.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    ResumeFileMapper resumeFileMapper;

    @Autowired
    StudentFileMapper studentFileMapper;

    @Autowired
    UploadLogMapper uploadLogMapper;


    @Override
    public String uploadFile(MultipartFile file, Integer uploaderId) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String filename = null;
        if (originalFilename != null) {
            filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        //file.transferTo(new File("C:\\Users\\86191\\Pictures\\temp\\"+filename));
        Student student = studentMapper.findByUserId(uploaderId);
        Integer studentId = student.getStudentId();
        String url = AliOssUtil.UploadFile(filename, file.getInputStream());
        File file1 = new File();
        file1.setFilePath(url);
        resumeFileMapper.insertFile(file1);
        studentFileMapper.insertStudentFile(studentId, file1.getFileId());
        UploadLog uploadLog = new UploadLog();
        uploadLog.setUploaderId(uploaderId);
        uploadLog.setFileId(file1.getFileId());
        Timestamp uploadTime = new Timestamp(System.currentTimeMillis());
        uploadLog.setUploadTime(uploadTime);
        uploadLogMapper.insertUploadLog(uploadLog);
        return url;
    }

    @Override
    public void deleteFile(Integer studentId, Integer fileId) {
        if(resumeFileMapper.findById(fileId) == null) {
            throw new RuntimeException("文件不存在");
        }
        if(studentFileMapper.findStudentIdByFileId(fileId) != studentId) {
            throw new RuntimeException("无权限");
        }
        studentFileMapper.deleteStudentFile(fileId);
        resumeFileMapper.deleteFile(fileId);
    }
}
